define([
	'../libs/zepto',
	'../common/base',
	'../common/common_click',
	'../common/dialog',
	'../common/yingSoftPrg',
	'../common/yingSoftCookie',
	'../common/ajax',
	'../common/yingSoftSetTest',
	'../common/maiDianApi'
],function(){
	if(_getClientType()=='web_iPhone'){
	}else{
		window.android.isPlayVideo('ss');
	}
	var knowledgeID=[];
	var userID = G_Cookie.getUserID();
	var guid = G_Cookie.getGuid();
	var chapterID = G_Prg.getQueryString('chapterID');
    var knowledgeID;
    var CptName = decodeURI(GetQueryString('chapterName'));
	heightDiv();
	getKnowledge(guid,chapterID);
	$('.footex').unbind('click').click(function(){
		var KnowledgeID=$(this).attr('KnowledgeID');
		var TestNums=$(this).attr('TestNums');
		if (TestNums == 0) {
            G_Prg.alert('该知识点无试题！');
            return;
        }else{
        	G_Cookie.setCptID(KnowledgeID);
        	if(_getClientType()!='web_iPhone'){
			}else{
				parent.window.location.href="iosvideostop://"+"@@";
			}
       		window.location.href="/answerExam?fromUrl=Five&chapterID="+chapterID+"&KnowledgeID="+KnowledgeID+"&chapterName=" + CptName;
        }
	})
	knowledegeMenu(0);
	var videoTab = $('#videoPlayer_0');
});
function knowledegeMenu(s){
	var userID = G_Cookie.getUserID();
	var guid = G_Cookie.getGuid();
	playKonledgeVideo(guid,knowledgeID[s],s);
}
function  NativePlayFunction(videlData){
    window.android.NativePlayFunction(videlData)//android
}
function getKnowledge(guid,chapterID) {  
    var chapterName = decodeURI(GetQueryString('chapterName'));
	$('.header').text(chapterName);
    var url = '/api/knowledge/getKnowledge';
    var params = {
        guid: guid,
        MaterialCptID: chapterID
    };
    G_AjaxApiVideo_OSS.post(url, params, false, function (json) {
        var jsonData = JSON.parse(json);
        if (jsonData.status === 200) {
            var data = jsonData.data;
            knowLedgeData = data.knowledge;
            knowledgeID = [];
            for(var i=0;i<knowLedgeData.length;i++){
            	knowledgeID.push(knowLedgeData[i].KnowledgeID);
            	var str='<div class="swiper-slide"><div class="wrap chapter_fix"><div class="top"><div class="titlevedio"><span id="countTotal">/'+knowLedgeData.length+'</span><span id="num">'+(i+1)+'</span>'
						+'<span class="titleF">'+knowLedgeData[i].Summary+'</span></div>'
						+'<div class="vedio"></div>'
						+'<div class="detals">详解：<span class="downloadA">下载视频</span></div>'
						+'<div class="titleT"></div></div>'
						+'<div class="warp"><div class="middle_1"><div>'
						+'<pre>'+ knowLedgeData[i].KnowledgeText+ '</pre>'
							+'</div></div></div><div class="footex" KnowledgeID='+knowLedgeData[i].KnowledgeID+' TestNums='+knowLedgeData[i].TestNums+'>考点练习题</div></div></div>'
          		$('.swiper-wrapper').append(str);
          		if(_getClientType()=='web_iPhone'){
          			$('.downloadA').css('display','none');
	      		}else{
	      		}
          		heightDiv();
            }
        } else if (jsonData.status === 201) {
            G_Prg.alert('知识点信息为空。');
        } else if (jsonData.status === 202) {
            if (!userID && !guid) {
                G_Prg.alert('请登录后查看更多内容。', function () {
                    window.location.href = '/login';
                });
                return;
            }
            G_Prg.alert('请购买后查看更多内容。', function () {
                window.location.href = '/recharge/byapp';
            });
        } else if (jsonData.status === 300) {
            G_Prg.alert('程序运行错误，knowledgeList. getKnowledge,数据库获取数据异常。', function () {
                //window.location.href = 'knowledgeChapter.html';
            });
        } else if (jsonData.status === 400) {
            G_Prg.alert('程序运行错误，knowledgeList. getKnowledge,参数错误。', function () {
                //window.location.href = 'knowledgeChapter.html';
            });
        } else {
            G_Prg.alert('抱歉，knowledgeList. getKnowledge，不能处理 status = "' + jsonData.status + '"！', function () {
                //window.location.href = 'knowledgeChapter.html';
            });
        }
    });
}
function playVideos(video,showingPage){
	$(".vedio").eq(showingPage).empty();
    //如果可以播放视频，则生成视频播放器，这样防止一些手机自己做的播放器不释放死机；
    var vedioStr = '<video id="videoPlayer_'+showingPage+'" autobuffer controls="controls" style="height: 200px;width:100%" >' +
        '<source id="video_mp4" data-setup="{}" poster="" autoplay controls autobuffer x-webkit-airplay="true" webkit-playsinline="true" src=' + video + ' type=\'video/mp4; codecs="avc1.42E01E, mp4a.40.2"\'>' +
        '抱歉，您的浏览器不支持video标签' +
        '</video>' ;
    $(".vedio").eq(showingPage).append(vedioStr);
    setTimeout(function(){
    	 $('.buffer').css('display','none');
    },100)
    var aa=$('video').eq(showingPage).attr('id');
	var ss=document.getElementById(aa);	
}
function _getClientType() {
    var browser = {
        versions: function () {
            var u = navigator.userAgent,
                app = navigator.appVersion;
            return {
                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
                android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1,
                iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1,
                iPad: u.indexOf('iPad') > -1,
                webApp: u.indexOf('Safari') == -1
            };
        }()
    };
    if (browser.versions.iPhone || browser.versions.iPad) {
        return 'web_iPhone';
    }
    if (browser.versions.ios || browser.versions.android || browser.versions.webApp) {
        return 'web_android';
    }
    return 'web_pc';
}
function playKonledgeVideo(guid,knowledgeID,showingPage) {
    var _success = function (json) {
        var jsonData = JSON.parse(json);
        if (jsonData.status === 200) {
        	if(_getClientType()=='web_iPhone'){
				$('.vedio').addClass('wedioIphone');
        	}else{
				playVideos(jsonData.data, showingPage)
			}
	      	$('.vedio').unbind('click').click(function(s){
				var videlData=JSON.stringify({
					"title":$('.swiper-slide').eq(showingPage).find('.titlevedio').find('span').eq(2).text(),
					'nkID':knowledgeID,
					"vidoeUrl":jsonData.data
				})
				var sss=encodeURI(videlData);
			//	NativePlayFunction(videlData);
				if(_getClientType()=='web_iPhone'){
					parent.window.location.href = "iosvideo://"+"@@"+sss;
				}else{
				}
			})
			$('.downloadA').unbind('click').click(function(){
				if(_getClientType()=='web_iPhone'){
//					parent.window.location.href = "iosvideo://"+"@@"+sss;
				}else{
					var knowledgeIDs=JSON.stringify(knowledgeID);
					var title=JSON.stringify($('.swiper-slide').eq(showingPage).find('.titlevedio').find('span').eq(2).text());
					var vidoeUrl=JSON.stringify(jsonData.data);
					window.video.downloadVideo(knowledgeIDs,vidoeUrl,title);
				}
	     	})
            return;
        } else {
            if (jsonData.status === 300) {
                G_Prg.alert('您没有该视频的播放权限');
                G_maiDian.setBugRecordInfos('程序错误', '视频目录——获取视频课程目录', jsonData.status + ':' + jsonData.msg);
                return;
            } else if (jsonData.status >= 400 && jsonData.status < 500) {
                G_maiDian.setBugRecordInfos('业务逻辑错误', '视频目录——获取视频课程目录', jsonData.status + ':' + jsonData.msg);
            } else {
                G_maiDian.setBugRecordInfos('其它程序错误', '视频目录——获取视频课程目录', jsonData.status + ':' + jsonData.msg);
            }
            G_Prg.throw('程序运行错误，不能处理，knowledge/getVideo=' + jsonData.status);
        }
    }
    var params = {
        guid: guid,
        KnowledgeID: knowledgeID
    };
    G_AjaxApiVideo_OSS.post('/api/knowledge/getVideo', params, false, _success);
}
//获取高度
function heightDiv(){
	var win=$(window).height();
	divH=win-$('.header').height()*2-$('.top').height();
	$('.middle_1').css('height',divH-50);
	$('.middle_1').css('overflow','auto');
//	$('.wrap').css('height','initial');
}

function GetQueryString(name) {  
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");  
    var r = window.location.search.substr(1).match(reg);  //获取url中"?"符后的字符串并正则匹配
    var context = "";  
    if (r != null)  
         context = r[2];  
    reg = null;  
    r = null;  
    return context == null || context == "" || context == "undefined" ? "" : context;  
}
